
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

package com.hlkj.pay.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.pojo.LocalContext;
import com.hlkj.framework.common.pojo.LocalRequest;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.adminuser.IUserPermissionAppService;
import com.hlkj.pay.common.AdminUserResultCode;
import com.hlkj.pay.common.constants.AdminConstant;
import com.hlkj.pay.dto.LocalAdminUserRequest;
import com.hlkj.pay.vo.admin.req.user.AdminUserCheckPermissionReq;
import com.hlkj.pay.vo.admin.resp.user.CheckPermissionResp;

import lombok.extern.slf4j.Slf4j;

/**
 * @author HlpayTeam
 * @data 2022/2/8 13:22
 */
@Component
@Slf4j
@Order
public class AdminUserPermissionInterceptor implements HandlerInterceptor {

    @Autowired
    @Lazy
    private IUserPermissionAppService userPermissionAppService;
    @Value("${spring.profiles.active}")
    private String active;
    private final MappingJackson2HttpMessageConverter errorHttpResponseConverter = new MappingJackson2HttpMessageConverter();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        // 获取客户端类型 ，小程序放行
        String clientType = request.getHeader(AdminConstant.CLIENT_TYPE);
        // 获取权限路由
        String permissionName = request.getHeader(AdminConstant.PERMISSION_NAME);
        String servletPath = request.getServletPath();
        if (StringUtils.isBlank(servletPath)) {
            servletPath = request.getPathInfo();
        }
        log.info("adminUserPermissionInterceptor:{}",servletPath);
        AdminUserCheckPermissionReq adminUserCheckPermissionReq = new AdminUserCheckPermissionReq();
        adminUserCheckPermissionReq.setPermissionName(permissionName);
        adminUserCheckPermissionReq.setUrl(servletPath);
        adminUserCheckPermissionReq.setMethod(request.getMethod());
        adminUserCheckPermissionReq.setClientType(clientType);
        CommonResult<CheckPermissionResp> respCommonResult = userPermissionAppService.checkPermission(
                adminUserCheckPermissionReq);
        LocalAdminUserRequest userRequest = (LocalAdminUserRequest)LocalContext.get();
        if (respCommonResult == null) {
            ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
            this.errorHttpResponseConverter.write(CommonResult.error(AdminUserResultCode.USER_PERMISSION_NOT_ACCESS), MediaType.APPLICATION_JSON, httpResponse);
            log.warn("checkPermission fail tenantId:{},userId:{},servletPath:{}", userRequest.getUserId(), JsonUtils.toJsonString(
                    adminUserCheckPermissionReq));
            return false;
        }
        if (!respCommonResult.isSuccess()&& !"local".equals(active)) {
            ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
            this.errorHttpResponseConverter.write(CommonResult.error(respCommonResult.getCode(), respCommonResult.getMsg()), MediaType.APPLICATION_JSON, httpResponse);
            log.warn("checkPermission fail tenantId:{},userId:{},servletPath:{}", userRequest.getUserId(), JsonUtils.toJsonString(
                    adminUserCheckPermissionReq));
            return false;
        }
        CheckPermissionResp checkPermissionResp = respCommonResult.getData();
        LocalRequest localRequest = LocalContext.get();
        LocalAdminUserRequest localAdminUserRequest = (LocalAdminUserRequest) localRequest;
        if(checkPermissionResp!=null){
            localAdminUserRequest.setPermissionCode(checkPermissionResp.getPermissionCode());
        }
        LocalContext.set(localAdminUserRequest);
        log.debug("login checkPermission info:{}", JsonUtils.toJsonString(localAdminUserRequest));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }

}
